# _*_ coding: utf-8 _*_

import json

from flask import request
from werkzeug.exceptions import HTTPException
from typing import NoReturn

from web_app.infrastructure.utils.http.responser import CODE

class APIException(HTTPException):
    code = 500  # http 状态码
    error_code = 40010  # 约定的异常码
    msg = CODE.get(error_code,'服务器未知错误')  # 异常信息

    def __init__(self, code=None, error_code=None, msg=None, headers=None) -> NoReturn:
        if code:
            self.code = code
        if error_code:
            self.error_code = error_code
        if msg:
            self.msg = msg
        super(APIException, self).__init__()

    def get_body(self, environ=None) -> json:
        body = dict(
            msg=self.msg,
            error_code=self.error_code,
            request_url=request.method + ' ' + self.get_url_no_param()
        )
        text = json.dumps(body)  # 返回文本
        return text

    def get_headers(self, environ=None):
        return [('Content-type', 'application/json; charset=utf-8')]

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')[0]
        return main_path


class ServerError(APIException):
    code = 500
    error_code = 40009
    msg = CODE.get(error_code,'服务器端异常')


class ParameterException(APIException):
    code = 400
    error_code = 10120
    msg = CODE.get(error_code,'参数错误')




